package com.caiyouxi.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.exception.ErrorCode;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.common.util.RandomUtil;
import com.caiyouxi.user.mapper.*;
import com.caiyouxi.user.model.*;
import com.caiyouxi.user.service.UserService;
import com.caiyouxi.user.util.CyxUtil;
import com.caiyouxi.user.util.message.MsgUtil;
import com.caiyouxi.user.util.message.SendSms;
import com.caiyouxi.user.util.Util;
import org.apache.log4j.Logger;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.random.R;
import org.nutz.mvc.Mvcs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/11.
 */

@Service
public class UserServiceImpl extends BaseService implements UserService{

    private Logger logger = Logger.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserAccountsMapper userAccountsMapper;

    @Autowired
    private UserAuthCodeMapper userAuthCodeMapper;

    @Autowired
    private UserRegLogsMapper userRegLogsMapper;

    @Autowired
    private UserLoginLogsMapper userLoginLogsMapper;

    @Autowired
    private  UserTokenMapper userTokenMapper;

    /**
     * TONKEN有效期
     */
    private  Long  validity = 2592000L;

    /**
     * 手机短信验证码登录
     */
    @Override
    @Transactional
    public ResData phone_login(PublicAttributeBean publicAttributeBean) {

        /**从缓存取验证码*/
        String key = buildAuthCodeRedisKey(publicAttributeBean.getPhone(), null, "LOGIN");
        if (!redisService.exists(key)){
            Log.e("缓存值不存在");
            return failed(ErrorCode.USER_AUTHCODE_TIME_LIMIT.getCode(),ErrorCode.USER_AUTHCODE_TIME_LIMIT.getMsg()+"缓存值不存在",null);
        }
        UserAuthCodeBean userAuthCodeThirdBean = Json.fromJson(UserAuthCodeBean.class, String.valueOf(redisService.get(key)));
        if(StringUtils.isEmpty(userAuthCodeThirdBean)){
            Log.e("UserAuthCodeBean不存在");
            return failed(ErrorCode.USER_AUTHCODE_TIME_LIMIT.getCode(),ErrorCode.USER_AUTHCODE_TIME_LIMIT.getMsg()+"UserAuthCodeBean不存在",null);
        }
        /**做验证*/
        if(!publicAttributeBean.getCode().equals(userAuthCodeThirdBean.getCode())){
            Log.e("验证码不正确");
            return failed(ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getCode(),ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getMsg(),null);
        }
        userAuthCodeThirdBean.setStatus("CONSUMED");
        userAuthCodeMapper.update_user_auth_code(userAuthCodeThirdBean);

        /**user_id存用户ID*/
        Integer user_id ;
        /**判断用户存不存在*/
        List<UserProfileBean> userProfileBeans=userMapper.get_user_profile_List(new UserProfileBean(publicAttributeBean.getPhone()));
        if(userProfileBeans.size() == 0){
            List<UserAccountsBean> newUserAccountsBeans = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(publicAttributeBean.getPhone(),"PHONE"));
            if (newUserAccountsBeans.size() == 0){
                Log.e("用户不存在正确");
                return failed(ErrorCode.USER_NOT_FOUND.getCode(), ErrorCode.USER_NOT_FOUND.getMsg(),null);
            }else {
                user_id =  newUserAccountsBeans.get(0).getUser_id();
            }
        }else {
            user_id =  userProfileBeans.get(0).getId();
        }

        /**获取用户信息*/
        UserProfileBean  userProfileBean  = userMapper.get_user_profile_info(new  UserProfileBean(user_id));
        /**创建新的登录日志*/
        UserLoginLogsBean userLoginLogsBean = new UserLoginLogsBean();
        userLoginLogsBean.setLogin_agent(Util.getAgent(Mvcs.getReq()));
        userLoginLogsBean.setLogin_source(CyxUtil.getLoginSource(publicAttributeBean.getPhone()));
        userLoginLogsBean.setLogin_app(publicAttributeBean.getApp_from());
        userLoginLogsBean.setUser_id(userProfileBean.getId());
        userLoginLogsBean.setLogin_time(Times.now());
        userLoginLogsBean.setLogin_ip(publicAttributeBean.getReq_ip());
        userLoginLogsMapper.add_user_login_logs(userLoginLogsBean);
        /**修改user的登录日志*/
        JSONObject loginLogsJosn = (JSONObject)JSONObject.toJSON(userLoginLogsBean);
        userProfileBean.setLast_login_log(loginLogsJosn.toJSONString());
        userMapper.update_user_profile(userProfileBean);
        /**创建令牌*/
        UserTokenBean userTokenBean  = new UserTokenBean();
        userTokenBean.setUser_id(userProfileBean.getId());
        userTokenBean = userTokenMapper.get_user_token(userTokenBean);
        UserTokenBean  newUserTokenBean =  new  UserTokenBean();
        newUserTokenBean.setCreate_time(Times.now());
        newUserTokenBean.setAccess_token(Lang.md5(userProfileBean + "|" + Times.getTS()));
        newUserTokenBean.setFailure_time(Times.nextDay(newUserTokenBean.getCreate_time(), 30));

        setToken(userTokenBean,newUserTokenBean,userProfileBean);


        /**设置返回参数*/
        ReturnAttributeBean ReturnAttributeBean = new ReturnAttributeBean();
        ReturnAttributeBean.setFailure_time(newUserTokenBean.getFailure_time().getTime() / 1000);
        ReturnAttributeBean.setToken(newUserTokenBean.getAccess_token());
        ReturnAttributeBean.setNickname(userProfileBean.getNickname());
        ReturnAttributeBean.setUser_id(userProfileBean.getId());
        ReturnAttributeBean.setAuth_status(CyxUtil.authStatus(userProfileBean.getAuth_status()));
        ReturnAttributeBean.setUsername(userProfileBean.getUsername());
        UserAccountsBean userAccountsBean = new UserAccountsBean();
        userAccountsBean.setUser_id(userProfileBean.getId());
        userAccountsBean.setSource("PHONE");
        List<UserAccountsBean> userAccountsBeans = userAccountsMapper.select_user_accounts_list(userAccountsBean);
        if (userAccountsBeans.size() != 0){
            UserAccountsBean   newuserAccountsBean=userAccountsBeans.get(0);
            ReturnAttributeBean.setBind_phone(newuserAccountsBean.getOpen_id());
        }

        UserAccountsBean userAccountsSecondBean = new UserAccountsBean();
        userAccountsSecondBean.setUser_id(userProfileBean.getId());
        userAccountsSecondBean.setOpen_id(publicAttributeBean.getPhone());
        List<UserAccountsBean> userAccountsFirstBeans= userAccountsMapper.select_user_accounts_list(userAccountsSecondBean);
        UserAccountsBean userAccountsThirdBeans ;
        if(userAccountsFirstBeans.size() !=0){
            userAccountsThirdBeans= userAccountsFirstBeans.get(0);
            userAccountsThirdBeans.setLast_log(loginLogsJosn.toJSONString());
            userAccountsMapper.update_user_accounts(userAccountsThirdBeans);
        }
        return success(ReturnAttributeBean);
    }






    /**
     * 用户名密码登录
     */
    @Override
    @Transactional
    public ResData login(PublicAttributeBean publicAttributeBean) {
        List<UserProfileBean> userProfileBeans=userMapper.get_user_profile_List(new UserProfileBean(publicAttributeBean.getUsername()));
        UserProfileBean userProfileFristBeans  ;
        /**判断用户存不存在*/
        if(userProfileBeans.size() == 0){
            Log.e("用户不存在");
            return failed(ErrorCode.USER_NOT_FOUND.getCode(), ErrorCode.USER_NOT_FOUND.getMsg(),null);
        }else {
            userProfileFristBeans =userProfileBeans.get(0);
        }
         /**将密码进行比较*/
        if (!Strings.equalsIgnoreCase(CyxUtil.buildPswd(publicAttributeBean.getPassword(), userProfileFristBeans.getSalt(), userProfileFristBeans.getPassword_algorithm()), userProfileFristBeans.getPassword())) {
            Log.e("密码不正确");
            return failed(ErrorCode.USER_USERNAME_PASSWORD_ERROR.getCode(),ErrorCode.USER_USERNAME_PASSWORD_ERROR.getMsg(),null);
        }
        /**创建新的登录日志*/
        UserLoginLogsBean userLoginLogsBean = new UserLoginLogsBean();
        userLoginLogsBean.setLogin_agent(Util.getAgent(Mvcs.getReq()));
        userLoginLogsBean.setLogin_source(CyxUtil.getLoginSource(publicAttributeBean.getUsername()));
        userLoginLogsBean.setLogin_app(publicAttributeBean.getApp_from());
        userLoginLogsBean.setUser_id(userProfileFristBeans.getId());
        userLoginLogsBean.setLogin_time(Times.now());
        userLoginLogsBean.setLogin_ip(publicAttributeBean.getReq_ip());
        userLoginLogsMapper.add_user_login_logs(userLoginLogsBean);

        /**修改user的登录日志*/
        JSONObject loginLogsJosn = (JSONObject)JSONObject.toJSON(userLoginLogsBean);
        userProfileFristBeans.setLast_login_log(loginLogsJosn.toJSONString());
        userMapper.update_user_profile(userProfileFristBeans);

        /**创建令牌*/
        UserTokenBean userTokenBean  = new UserTokenBean();
        userTokenBean.setUser_id(userProfileFristBeans.getId());
        userTokenBean = userTokenMapper.get_user_token(userTokenBean);
        UserTokenBean  newUserTokenBean =  new  UserTokenBean();
        newUserTokenBean.setCreate_time(Times.now());
        logger.info("时间"+Times.now());
        newUserTokenBean.setAccess_token(Lang.md5(userProfileFristBeans + "|" + Times.getTS()));
        newUserTokenBean.setFailure_time(Times.nextDay(newUserTokenBean.getCreate_time(), 30));
        logger.info("时间"+Times.nextDay(newUserTokenBean.getCreate_time(), 10));

        setToken(userTokenBean,newUserTokenBean,userProfileFristBeans);



        /**设置返回参数*/
        ReturnAttributeBean ReturnAttributeBean = new ReturnAttributeBean();
        ReturnAttributeBean.setFailure_time(newUserTokenBean.getFailure_time().getTime() / 1000);
        ReturnAttributeBean.setToken(newUserTokenBean.getAccess_token());
        ReturnAttributeBean.setNickname(userProfileFristBeans.getNickname());
        ReturnAttributeBean.setUser_id(userProfileFristBeans.getId());
        ReturnAttributeBean.setAuth_status(CyxUtil.authStatus(userProfileFristBeans.getAuth_status()));
        ReturnAttributeBean.setAccount(new AccountBean(publicAttributeBean.getUsername(), publicAttributeBean.getPassword()));
        ReturnAttributeBean.setUsername(userProfileFristBeans.getUsername());
        List<UserAccountsBean> userAccountsBeans = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(userProfileFristBeans.getId(),"PHONE"));
        if (userAccountsBeans.size() != 0){
            UserAccountsBean   newUserAccountsBean=userAccountsBeans.get(0);
            ReturnAttributeBean.setBind_phone(newUserAccountsBean.getOpen_id());
        }

        if (Strings.isEmail(publicAttributeBean.getUsername()) || Strings.isMobile(publicAttributeBean.getUsername())) {
            UserAccountsBean userAccountsSecondBean = new UserAccountsBean();
            userAccountsSecondBean.setUser_id(userProfileFristBeans.getId());
            userAccountsSecondBean.setOpen_id(publicAttributeBean.getUsername());
            List<UserAccountsBean> userAccountsFirstBeans= userAccountsMapper.select_user_accounts_list(userAccountsSecondBean);
            UserAccountsBean userAccountsThirdBean ;
            if(userAccountsFirstBeans.size() !=0){
                userAccountsThirdBean= userAccountsFirstBeans.get(0);
                userAccountsThirdBean.setLast_log(loginLogsJosn.toJSONString());
                userAccountsMapper.update_user_accounts(userAccountsThirdBean);
            }
        }
        return success(ReturnAttributeBean);
    }

    /**
     * 根据TOKEN查询用户
     */
    @Override
    public ResData get_by_token(PublicAttributeBean publicAttributeBean) {
      /*  *//**从缓存取验证码*//*
        String key ="user:token:" + userTokenBean.getUser_id();
        if (!redisService.exists(key)){
            Log.e("缓存值不存在");
            return failed(ErrorCode.USER_TOKEN_EXPIRED.getCode(),ErrorCode.USER_TOKEN_EXPIRED.getMsg(),null);
        }

        UserTokenBean fisrtUserTokenBean = Json.fromJson(UserTokenBean.class, String.valueOf(redisService.get(key)));
        if(StringUtils.isEmpty(userTokenBean)){
            Log.e("UserTokenBean不存在");
            return failed(ErrorCode.USER_TOKEN_EXPIRED.getCode(),ErrorCode.USER_TOKEN_EXPIRED.getMsg(),null);
        }
        *//** 判断是不是过期*//*
        if (!userTokenBean.getAccess_token().equals(fisrtUserTokenBean.getAccess_token())){

        }*/
            UserTokenBean userTokenBean=new UserTokenBean();
            userTokenBean.setUser_id(publicAttributeBean.getUser_id());
            userTokenBean.setAccess_token(publicAttributeBean.getToken());
            UserTokenBean newUserTokenBean=userTokenMapper.get_user_token(userTokenBean);
            /** 判断是不是过期*/
            if (StringUtils.isEmpty(newUserTokenBean)){
                Log.e("UserTokenBean不存在");
                return failed(ErrorCode.USER_TOKEN_EXPIRED.getCode(),ErrorCode.USER_TIME_OUT.getMsg(),null);
            }
            /** 判断是不是过期*/
            if (!userTokenBean.getAccess_token().equals(newUserTokenBean.getAccess_token())){
                Log.e("过期");
                return failed(ErrorCode.USER_TOKEN_EXPIRED.getCode(),ErrorCode.USER_TIME_OUT.getMsg(),null);
            }

        UserProfileBean   userProfileBean=  userMapper.get_user_profile_info(new UserProfileBean(userTokenBean.getUser_id()));
        PublicAttributeBean PublicAttributeBean = new PublicAttributeBean();
        PublicAttributeBean.setId(userProfileBean.getId());
        PublicAttributeBean.setUsername(userProfileBean.getUsername());
        PublicAttributeBean.setNickname(userProfileBean.getNickname());
        PublicAttributeBean.setRealname(userProfileBean.getRealname());
        PublicAttributeBean.setPicture(userProfileBean.getPicture());
        boolean isAuth = false;
        if (CyxUtil.authStatus(userProfileBean.getAuth_status())){
            isAuth = true;
        }
        PublicAttributeBean.setAuth(isAuth);
        //查询用户绑定的手机
        UserAccountsBean newuserAccountsBean = userAccountsMapper.select_user_accounts_info(new UserAccountsBean(userTokenBean.getUser_id(),"PHONE"));
        if (!StringUtils.isEmpty(newuserAccountsBean)){
            PublicAttributeBean.setBind_phone(newuserAccountsBean.getOpen_id());
        }
        return success(PublicAttributeBean);
    }


    /**
     * 用户邮箱注册
     */
    @Override
    @Transactional
    public ResData email_reg(PublicAttributeBean publicAttributeBean) {
        /**判断是不是用户名被注册*/
        List<UserProfileBean> userProfileBeans=userMapper.get_user_profile_List(new UserProfileBean(publicAttributeBean.getEmail()));
        if(userProfileBeans.size() != 0){
            Log.e("用户已存在");
            return failed(ErrorCode.USER_FOUND.getCode(),ErrorCode.USER_FOUND.getMsg(),null);
        }
        /**在判断邮箱是否绑定*/
        List<UserAccountsBean>userAccountsBeans = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(publicAttributeBean.getEmail(),"EMAIL"));
        if(userAccountsBeans.size() != 0){
            Log.e("邮箱已存在");
            return failed(ErrorCode.EMAIL_IS_BINDING.getCode(),ErrorCode.EMAIL_IS_BINDING.getMsg(),null);
        }
        /**从缓存中取出注册验证码*/
        /*String key =buildAuthCodeRedisKey(PublicAttributeBean.getPhone(), Integer.valueOf(PublicAttributeBean.getPhone()), "code");
        if (!redisService.exists(key)){
          return failed(ErrorCode.USER_AUTHCODE_TIME_LIMIT.getCode(),ErrorCode.USER_AUTHCODE_TIME_LIMIT.getMsg(),null);
        }
        UserAuthCodeBean userAuthCodeThirdBean = Json.fromJson(UserAuthCodeBean.class, String.valueOf(redisService.get(key)));*/
        UserAuthCodeBean userAuthCodeThirdBean = new UserAuthCodeBean();
        /**先注册验证码为666666*/
        userAuthCodeThirdBean.setCode("666666");
        if(!publicAttributeBean.getCode().equals(userAuthCodeThirdBean.getCode())){
            Log.e("验证码不匹配");
            return failed(ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getCode(),ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getMsg(),null);
        }
        userAuthCodeThirdBean.setStatus("CONSUMED");
        userAuthCodeMapper.update_user_auth_code(userAuthCodeThirdBean);


        UserProfileBean newUserProfileBean = new UserProfileBean();
        String password = R.captchaNumber(6);
        newUserProfileBean.setUsername(publicAttributeBean.getEmail());
        newUserProfileBean.setNickname(publicAttributeBean.getEmail());
        newUserProfileBean.setPassword_algorithm("MD5");
        newUserProfileBean.setSalt(R.UU64());
        newUserProfileBean.setRealname("");
        newUserProfileBean.setId_card("");
        newUserProfileBean.setLast_login_log(null);
        newUserProfileBean.setAuth_status("");
        newUserProfileBean.setStatus("NORMAL");
        newUserProfileBean.setPassword(CyxUtil.buildPswd(password, newUserProfileBean.getSalt(), newUserProfileBean.getPassword_algorithm()));

        UserRegLogBean userRegLogBean  =new UserRegLogBean();
        userRegLogBean.setApp_from(publicAttributeBean.getApp_from());
        JSONObject deviceJson =(JSONObject)JSONObject.toJSON(publicAttributeBean.getDevice());
        userRegLogBean.setDevice(deviceJson.toJSONString());
        userRegLogBean.setInvite(null);
        userRegLogBean.setReg_agent(Util.getAgent(Mvcs.getReq()));
        userRegLogBean.setPromo_code(null);
        userRegLogBean.setReg_time(Times.now());
        userRegLogBean.setReg_ip(publicAttributeBean.getReq_ip());


        userRegLogBean.setChannel(setSdk(publicAttributeBean));

        userRegLogBean.setSource("EMAIL");
        userRegLogBean.setUser_id(null);

        JSONObject userRegLogJson =(JSONObject)JSONObject.toJSON(userRegLogBean);
        userRegLogJson.put("req_loaction",publicAttributeBean.getReq_loaction());/**根据淘宝获取,从前面传过来User*/

        /**存为存入User*/
        newUserProfileBean.setReg_log(userRegLogJson.toJSONString());
        userMapper.add_user_profile(newUserProfileBean);
        userRegLogBean.setUser_id(newUserProfileBean.getId());
        userRegLogsMapper.add_reg_logs(userRegLogBean);

        UserAccountsBean userAccountsBean = new UserAccountsBean();
        userAccountsBean.setUser_id(newUserProfileBean.getId());
        userAccountsBean.setOpen_id(publicAttributeBean.getEmail());
        userAccountsBean.setAccess_token(userAuthCodeThirdBean.getCode());
        userAccountsBean.setSource("EMAIL");
        userAccountsBean.setAuth_protocol("SMSCODE|PASSWORD");
        userAccountsBean.setNickname(publicAttributeBean.getEmail());
        userAccountsBean.setBind_time(Times.now());
        userAccountsBean.setToken_create_time(Times.now());
        userAccountsBean.setToken_expire_time(Times.nextYear(userAccountsBean.getToken_create_time(), 99));
        userAccountsBean.setForbidden_Login_areas(null);
        userAccountsBean.setLast_log(null);
        userAccountsBean.setData(null);
        userAccountsMapper.add_user_accounts(userAccountsBean);

        Map<String, Object> data = new HashMap<>();
        data.put("username", newUserProfileBean.getUsername());
        data.put("password", password);

        return success(data);
    }


    /**
     * 邮箱验证登录
     */
    @Override
    @Transactional
    public ResData email_login(PublicAttributeBean publicAttributeBean) {
        /**从缓存取验证码*/
        /*String key = buildAuthCodeRedisKey(PublicAttributeBean.getEmail(), null, "LOGIN");
        if (!redisService.exists(key)){
            return failed(ErrorCode.USER_AUTHCODE_TIME_LIMIT.getCode(),ErrorCode.USER_AUTHCODE_TIME_LIMIT.getMsg(),null);
        }
        UserAuthCodeBean userAuthCodeThirdBean = Json.fromJson(UserAuthCodeBean.class, String.valueOf(redisService.get(key)));*/
        UserAuthCodeBean userAuthCodeThirdBean = new UserAuthCodeBean();
        /**先注册验证码为666666*/
        userAuthCodeThirdBean.setCode("666666");
        if(!publicAttributeBean.getCode().equals(userAuthCodeThirdBean.getCode())){
            Log.e("验证码不匹配");
            return failed(ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getCode(),ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getMsg(),null);
        }
        userAuthCodeThirdBean.setStatus("CONSUMED");
        userAuthCodeMapper.update_user_auth_code(userAuthCodeThirdBean);
        /**user_id存用户ID*/
        Integer user_id ;
        /**判断用户存不存在*/
        List<UserProfileBean> userProfileBeans=userMapper.get_user_profile_List(new UserProfileBean(publicAttributeBean.getEmail()));
        if(userProfileBeans.size() == 0){
            List<UserAccountsBean> newUserAccountsBeans = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(publicAttributeBean.getEmail(),"EAMAL"));
            if (newUserAccountsBeans.size() == 0){
                Log.e("newUserAccountsBeans不存在");
                return failed(ErrorCode.USER_NOT_FOUND.getCode(), ErrorCode.USER_NOT_FOUND.getMsg(),null);
            }else {
                user_id =  newUserAccountsBeans.get(0).getUser_id();
            }
        }else {
            user_id =  userProfileBeans.get(0).getId();
        }
        /**获取用户信息*/
        UserProfileBean  userProfileBean  = userMapper.get_user_profile_info(new UserProfileBean(user_id));
        /**创建新的登录日志*/
        UserLoginLogsBean userLoginLogsBean = new UserLoginLogsBean();
        userLoginLogsBean.setLogin_agent(Util.getAgent(Mvcs.getReq()));
        userLoginLogsBean.setLogin_source(CyxUtil.getLoginSource(publicAttributeBean.getEmail()));
        userLoginLogsBean.setLogin_app(publicAttributeBean.getApp_from());
        userLoginLogsBean.setUser_id(userProfileBean.getId());
        userLoginLogsBean.setLogin_time(Times.now());
        userLoginLogsBean.setLogin_ip(publicAttributeBean.getReq_ip());
        userLoginLogsMapper.add_user_login_logs(userLoginLogsBean);
        /**修改user的登录日志*/
        JSONObject loginLogsJosn = (JSONObject)JSONObject.toJSON(userLoginLogsBean);
        userProfileBean.setLast_login_log(loginLogsJosn.toJSONString());
        userMapper.update_user_profile(userProfileBean);
        /**创建令牌*/
        UserTokenBean userTokenBean  = new UserTokenBean();
        userTokenBean.setUser_id(userProfileBean.getId());
        userTokenBean = userTokenMapper.get_user_token(userTokenBean);
        UserTokenBean  newUserTokenBean =  new  UserTokenBean();
        newUserTokenBean.setCreate_time(Times.now());
        logger.info("时间"+Times.now());
        newUserTokenBean.setAccess_token(Lang.md5(userProfileBean + "|" + Times.getTS()));
        logger.info("时间"+Lang.md5(userProfileBean + "|" + Times.getTS()));
        newUserTokenBean.setFailure_time(Times.nextDay(newUserTokenBean.getCreate_time(), 30));
        logger.info("时间"+Times.nextDay(newUserTokenBean.getCreate_time(), 10));


        setToken(userTokenBean,newUserTokenBean,userProfileBean);


        /**设置返回参数*/
        ReturnAttributeBean ReturnAttributeBean = new ReturnAttributeBean();
        ReturnAttributeBean.setFailure_time(newUserTokenBean.getFailure_time().getTime() / 1000);
        ReturnAttributeBean.setToken(newUserTokenBean.getAccess_token());
        ReturnAttributeBean.setNickname(userProfileBean.getNickname());
        ReturnAttributeBean.setUser_id(userProfileBean.getId());
        ReturnAttributeBean.setAuth_status(CyxUtil.authStatus(userProfileBean.getAuth_status()));
        ReturnAttributeBean.setUsername(userProfileBean.getUsername());
        UserAccountsBean userAccountsBean = new UserAccountsBean();
        userAccountsBean.setUser_id(userProfileBean.getId());
        userAccountsBean.setSource("EAMAL");
        List<UserAccountsBean> userAccountsBeans = userAccountsMapper.select_user_accounts_list(userAccountsBean);
        if (userAccountsBeans.size() != 0){
            UserAccountsBean   newuserAccountsBean=userAccountsBeans.get(0);
            ReturnAttributeBean.setBind_phone(newuserAccountsBean.getOpen_id());
        }
        UserAccountsBean userAccountsSecondBean = new UserAccountsBean();
        userAccountsSecondBean.setUser_id(userProfileBean.getId());
        userAccountsSecondBean.setOpen_id(publicAttributeBean.getEmail());
        List<UserAccountsBean> userAccountsFirstBeans= userAccountsMapper.select_user_accounts_list(userAccountsSecondBean);
        UserAccountsBean userAccountsThirdBean;
        if(userAccountsFirstBeans.size() !=0){
            userAccountsThirdBean= userAccountsFirstBeans.get(0);
            userAccountsThirdBean.setLast_log(loginLogsJosn.toJSONString());
            userAccountsMapper.update_user_accounts(userAccountsThirdBean);
        }

        return success(ReturnAttributeBean);

    }


    /**
     * 修改密码
     */
    @Override
    @Transactional
    public ResData change_password(PublicAttributeBean publicAttributeBean) {
        UserProfileBean newUserProfileBean  = userMapper.get_user_profile_info(new UserProfileBean(publicAttributeBean.getUser_id()));
        /**判断用户存不存在*/
        if (StringUtils.isEmpty(newUserProfileBean)){
            Log.e("用户不存在");
            return failed(ErrorCode.USER_NOT_FOUND.getCode(), ErrorCode.USER_NOT_FOUND.getMsg(),null);
        }
        /**判断原密码是不是相同*/
        if (!Strings.equalsIgnoreCase(CyxUtil.buildPswd(publicAttributeBean.getOld_password(), newUserProfileBean.getSalt(), newUserProfileBean.getPassword_algorithm()), newUserProfileBean.getPassword())) {
            Log.e("密码不相同");
            return failed(ErrorCode.USER_USERNAME_PASSWORD_ERROR.getCode(),ErrorCode.USER_USERNAME_PASSWORD_ERROR.getMsg(),null);
        }
        newUserProfileBean.setPassword_algorithm("MD5");
        newUserProfileBean.setSalt(R.UU64());
        String newPassword =CyxUtil.buildPswd(publicAttributeBean.getPassword(), newUserProfileBean.getSalt(), newUserProfileBean.getPassword_algorithm()) ;
        newUserProfileBean.setPassword(newPassword);
        int result = userMapper.update_user_profile(newUserProfileBean);
        if(result == 1){
            return success(null);
        }
        return failed(ErrorCode.SYS_BUSSINESS_ERROR.getCode(),ErrorCode.SYS_BUSSINESS_ERROR.getMsg(),null);
    }


    /**
     * 修改昵称
     */
    @Override
    @Transactional
    public ResData change_nickname(PublicAttributeBean publicAttributeBean) {
        UserProfileBean newUserProfileBean  = userMapper.get_user_profile_info(new UserProfileBean(publicAttributeBean.getUser_id()));
        if (StringUtils.isEmpty(newUserProfileBean)){
            Log.e("用户不存在");
            return failed(ErrorCode.USER_NOT_FOUND.getCode(), ErrorCode.USER_NOT_FOUND.getMsg(),null);
        }
        if (publicAttributeBean.getNickname().equals(newUserProfileBean.getNickname())){
            Log.e("昵称相同");
            return failed(ErrorCode.USER_NAME_FOUND.getCode(), ErrorCode.USER_NAME_FOUND.getMsg(),null);
        }
        newUserProfileBean.setNickname(publicAttributeBean.getNickname());
        int result = userMapper.update_user_profile(newUserProfileBean);
        if(result == 1){
            return success(null);
        }
        return failed(ErrorCode.SYS_BUSSINESS_ERROR.getCode(),ErrorCode.SYS_BUSSINESS_ERROR.getMsg(),null);
    }


    /**
     * 绑定换绑定手机
     */
    @Override
    @Transactional
    public ResData bind_phone(PublicAttributeBean publicAttributeBean) {
       List<UserAccountsBean> uUserAccountsBeans=userAccountsMapper.select_user_accounts_list(new UserAccountsBean(publicAttributeBean.getUser_id(),"PHONE"));
        UserAccountsBean newUserAccountsBean = new  UserAccountsBean();
        if (uUserAccountsBeans.size()==0){
            //如果为空，则插入
            newUserAccountsBean.setUser_id(publicAttributeBean.getUser_id());
            newUserAccountsBean.setOpen_id(publicAttributeBean.getPhone());
            newUserAccountsBean.setAccess_token("");
            newUserAccountsBean.setSource("PHONE");
            newUserAccountsBean.setAuth_protocol("SMSCODE|PASSWORD");
            newUserAccountsBean.setNickname(publicAttributeBean.getPhone());
            newUserAccountsBean.setBind_time(Times.now());
            newUserAccountsBean.setToken_create_time(Times.now());
            newUserAccountsBean.setToken_expire_time(Times.nextYear(newUserAccountsBean.getToken_create_time(), 99));
            newUserAccountsBean.setForbidden_Login_areas(null);
            newUserAccountsBean.setLast_log(null);
            newUserAccountsBean.setData(null);
            userAccountsMapper.add_user_accounts(newUserAccountsBean);
        }else {
            UserAccountsBean uUserAccountsBean = uUserAccountsBeans.get(0);
            uUserAccountsBean.setOpen_id(publicAttributeBean.getPhone());
            userAccountsMapper.update_user_accounts(uUserAccountsBean);
        }
        return success(null);
    }

    /**
     * 一键注册
     */
    @Override
    @Transactional
    public ResData auto_reg(PublicAttributeBean publicAttributeBean) {
        /**生成用户名*/
        String f="ssSSS";
        String username = "cyx"+new SimpleDateFormat(f).format(new Date())+ RandomUtil.get_num_random();
        logger.info(username);

        /**生成用户*/
        UserProfileBean newUserProfileBean = new UserProfileBean();
        String password = R.captchaNumber(6);
        newUserProfileBean.setUsername(username);
        newUserProfileBean.setNickname(username);
        newUserProfileBean.setPassword_algorithm("MD5");
        newUserProfileBean.setSalt(R.UU64());
        newUserProfileBean.setRealname("");
        newUserProfileBean.setId_card("");
        newUserProfileBean.setLast_login_log(null);
        newUserProfileBean.setAuth_status("");
        newUserProfileBean.setStatus("NORMAL");
        newUserProfileBean.setPassword(CyxUtil.buildPswd(password, newUserProfileBean.getSalt(), newUserProfileBean.getPassword_algorithm()));

        /**生成注册日志*/
        UserRegLogBean userRegLogBean  =new UserRegLogBean();
        JSONObject deviceJson =(JSONObject)JSONObject.toJSON(publicAttributeBean.getDevice());
        userRegLogBean.setDevice(deviceJson.toJSONString());
        userRegLogBean.setInvite(null);
        userRegLogBean.setReg_agent(Util.getAgent(Mvcs.getReq()));
        userRegLogBean.setPromo_code(null);
        userRegLogBean.setReg_time(Times.now());
        userRegLogBean.setApp_from(publicAttributeBean.getApp_from());
        userRegLogBean.setReg_ip(publicAttributeBean.getReq_ip());

        userRegLogBean.setChannel(setSdk(publicAttributeBean));

        userRegLogBean.setSource("USERNAME");
        JSONObject userReglogJson =(JSONObject)JSONObject.toJSON(userRegLogBean);
        userReglogJson.put("req_loaction", publicAttributeBean.getReq_loaction());/**根据淘宝获取,从前面传过来User*/

        /**存为存入User*/
        newUserProfileBean.setReg_log(userReglogJson.toJSONString());
        userMapper.add_user_profile(newUserProfileBean);
        userRegLogBean.setUser_id(newUserProfileBean.getId());
        userRegLogsMapper.add_reg_logs(userRegLogBean);

        Map<String, Object> data = new HashMap<>();
        data.put("username",username);
        data.put("password", password);

        return success(data);
    }



    /**
     * 自动登录
     */
    @Override
    @Transactional
    public ResData auto_login(PublicAttributeBean publicAttributeBean){
        /**判断用户存不存在*/
        UserProfileBean userProfileBean = new UserProfileBean();
        userProfileBean.setId(publicAttributeBean.getUser_id());
        userProfileBean=userMapper.get_user_profile_info(userProfileBean);
        if(StringUtils.isEmpty(userProfileBean)){
            Log.e("用户不存在");
            return failed(ErrorCode.USER_NOT_FOUND.getCode(), ErrorCode.USER_NOT_FOUND.getMsg(),null);
        }
        /**操作缓存*/
        logger.info("key为"+publicAttributeBean.getUser_id());
        String key = "user:token:" + publicAttributeBean.getUser_id();
        if (!redisService.exists(key)){
            Log.e("超时");
            return failed(ErrorCode.USER_AUTHCODE_TIME_LIMIT.getCode(),ErrorCode.USER_AUTHCODE_TIME_LIMIT.getMsg(),null);
        }
        /**从缓存Token*/
        UserTokenBean userTokenBean = Json.fromJson(UserTokenBean.class, String.valueOf(redisService.get(key)));
        if(StringUtils.isEmpty(userTokenBean)){
            Log.e("Token不存在");
            return failed(ErrorCode.USER_TOKEN_EXPIRED.getCode(),ErrorCode.USER_TOKEN_EXPIRED.getMsg(),null);
        }
        /**创建新的登录日志*/
        UserLoginLogsBean userLoginLogsBean = new UserLoginLogsBean();
        userLoginLogsBean.setLogin_agent(Util.getAgent(Mvcs.getReq()));
        userLoginLogsBean.setLogin_source(CyxUtil.getLoginSource(publicAttributeBean.getUser_id().toString()));
        userLoginLogsBean.setUser_id(userProfileBean.getId());
        userLoginLogsBean.setLogin_time(Times.now());
        userLoginLogsBean.setLogin_app(publicAttributeBean.getApp_from());
        userLoginLogsBean.setLogin_ip(publicAttributeBean.getReq_ip());
        userLoginLogsMapper.add_user_login_logs(userLoginLogsBean);
        /**修改user的登录日志*/
        JSONObject loginLogsJosn = (JSONObject)JSONObject.toJSON(userLoginLogsBean);
        userProfileBean.setLast_login_log(loginLogsJosn.toJSONString());
        userMapper.update_user_profile(userProfileBean);
        /**修改令牌有效期*/
        userTokenBean.setFailure_time(Times.nextDay(Times.now(), 30));
        userTokenMapper.update_user_token(userTokenBean);
        redisService.set("user:token:" + userTokenBean.getUser_id(), Json.toJson(userTokenBean), validity);
        /**设置返回参数*/
        ReturnAttributeBean ReturnAttributeBean = new ReturnAttributeBean();
        ReturnAttributeBean.setFailure_time(userTokenBean.getFailure_time().getTime() / 1000);
        ReturnAttributeBean.setToken(userTokenBean.getAccess_token());
        ReturnAttributeBean.setRealname(userProfileBean.getRealname());
        ReturnAttributeBean.setUser_id(userProfileBean.getId());
        ReturnAttributeBean.setNickname(userProfileBean.getNickname());
        ReturnAttributeBean.setUsername(userProfileBean.getUsername());
        ReturnAttributeBean.setAuth_status(CyxUtil.authStatus(userProfileBean.getAuth_status()));
        /**取open_id值*/
        List<UserAccountsBean> userAccountsBeans = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(userProfileBean.getId(),"PHONE"));
        if (userAccountsBeans.size() != 0){
            UserAccountsBean  newUserAccountsBean = userAccountsBeans.get(0);
            ReturnAttributeBean.setBind_phone(newUserAccountsBean.getOpen_id());
        }

        return success(ReturnAttributeBean);
    }




    /**
     * 用户手机号码注册
     */
    @Override
    @Transactional
    public ResData phone_reg(PublicAttributeBean publicAttributeBean){
        /**判断是不是用户名被注册*/
        List<UserProfileBean> userProfileBeans=userMapper.get_user_profile_List(new UserProfileBean(publicAttributeBean.getPhone()));
        if(userProfileBeans.size() != 0){
            Log.e("用户存在");
            return failed(ErrorCode.USER_FOUND.getCode(),ErrorCode.USER_FOUND.getMsg(),null);
        }
        /**在判断手机号是否绑定*/
        List<UserAccountsBean>userAccountsBeans = userAccountsMapper.select_user_accounts_list( new UserAccountsBean(publicAttributeBean.getPhone(),"PHONE"));
        if(userAccountsBeans.size() != 0){
            Log.e("手机已绑定");
            return failed(ErrorCode.PHONE_IS_BINDING.getCode(),ErrorCode.PHONE_IS_BINDING.getMsg(),null);
        }
        /**从缓存取验证码*/
        String key = buildAuthCodeRedisKey(publicAttributeBean.getPhone(), null, "REG");
        if (!redisService.exists(key)){
            Log.e("缓存值不存在");
            return failed(ErrorCode.USER_AUTHCODE_TIME_LIMIT.getCode(),ErrorCode.USER_AUTHCODE_TIME_LIMIT.getMsg(),null);
        }
        UserAuthCodeBean userAuthCodeThirdBean = Json.fromJson(UserAuthCodeBean.class, String.valueOf(redisService.get(key)));
        if(StringUtils.isEmpty(userAuthCodeThirdBean)){
            Log.e("UserAuthCodeBean不存在");
            return failed(ErrorCode.USER_AUTHCODE_TIME_LIMIT.getCode(),ErrorCode.USER_AUTHCODE_TIME_LIMIT.getMsg(),null);
        }
        /**判断验证码是不是有效*/
        if(!publicAttributeBean.getCode().equals(userAuthCodeThirdBean.getCode())){
            Log.e("验证码不匹配");
            return failed(ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getCode(),ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getMsg(),null);
        }
        userAuthCodeThirdBean.setStatus("CONSUMED");
        userAuthCodeMapper.update_user_auth_code(userAuthCodeThirdBean);

        UserProfileBean newUserProfileBean = new UserProfileBean();
        String password = R.captchaNumber(6);
        newUserProfileBean.setUsername(publicAttributeBean.getPhone());
        newUserProfileBean.setNickname(publicAttributeBean.getPhone());
        newUserProfileBean.setPassword_algorithm("MD5");
        newUserProfileBean.setSalt(R.UU64());
        newUserProfileBean.setRealname("");
        newUserProfileBean.setId_card("");
        newUserProfileBean.setLast_login_log(null);
        newUserProfileBean.setAuth_status("");
        newUserProfileBean.setStatus("NORMAL");
        newUserProfileBean.setPassword(CyxUtil.buildPswd(password, newUserProfileBean.getSalt(), newUserProfileBean.getPassword_algorithm()));

        UserRegLogBean userRegLogBean  =new UserRegLogBean();
        userRegLogBean.setApp_from(publicAttributeBean.getApp_from());
        JSONObject deviceJson =(JSONObject)JSONObject.toJSON(publicAttributeBean.getDevice());
        userRegLogBean.setDevice(deviceJson.toJSONString());
        userRegLogBean.setInvite(null);
        userRegLogBean.setReg_agent(Util.getAgent(Mvcs.getReq()));
        userRegLogBean.setPromo_code(null);
        userRegLogBean.setReg_time(Times.now());
        userRegLogBean.setReg_ip(publicAttributeBean.getReq_ip());
        userRegLogBean.setChannel(setSdk(publicAttributeBean));
        userRegLogBean.setSource("PHONE");

        JSONObject userReglogJson =(JSONObject)JSONObject.toJSON(userRegLogBean);
        userReglogJson.put("req_loaction",publicAttributeBean.getReq_loaction());/**根据淘宝获取,从前面传过来User*/

        /**存为存入User*/
        newUserProfileBean.setReg_log(userReglogJson.toJSONString());
        userMapper.add_user_profile(newUserProfileBean);
        userRegLogBean.setUser_id(newUserProfileBean.getId());
        userRegLogsMapper.add_reg_logs(userRegLogBean);

        UserAccountsBean userAccountsBean = new UserAccountsBean();
        userAccountsBean.setUser_id(newUserProfileBean.getId());
        userAccountsBean.setOpen_id(publicAttributeBean.getPhone());
        userAccountsBean.setAccess_token(userAuthCodeThirdBean.getCode());
        userAccountsBean.setSource("PHONE");
        userAccountsBean.setAuth_protocol("SMSCODE|PASSWORD");
        userAccountsBean.setNickname(publicAttributeBean.getPhone());
        userAccountsBean.setBind_time(Times.now());
        userAccountsBean.setToken_create_time(Times.now());
        userAccountsBean.setToken_expire_time(Times.nextYear(userAccountsBean.getToken_create_time(), 99));
        userAccountsBean.setForbidden_Login_areas(null);
        userAccountsBean.setLast_log(null);
        userAccountsBean.setData(null);
        userAccountsMapper.add_user_accounts(userAccountsBean);

        Map<String, Object> data = new HashMap<>();
        data.put("username", newUserProfileBean.getUsername());
        data.put("password", password);

        return success(data);
    }



    /**
     * 用户名注册
     */
    @Override
    @Transactional
    public ResData reg(PublicAttributeBean publicAttributeBean) {

        /**判断是不是用户名被注册*/
        List<UserProfileBean> userProfileBeans=userMapper.get_user_profile_List(new UserProfileBean(publicAttributeBean.getUsername()));
        if(userProfileBeans.size() != 0){
            Log.e("用户名已存在");
            return failed(ErrorCode.USER_FOUND.getCode(),ErrorCode.USER_FOUND.getMsg(),null);
        }

        UserProfileBean userProfileBean = new UserProfileBean();
        userProfileBean.setUsername(publicAttributeBean.getUsername());
        userProfileBean.setNickname(publicAttributeBean.getUsername());
        userProfileBean.setPassword_algorithm("MD5");
        userProfileBean.setSalt(R.UU64());
        userProfileBean.setRealname("");
        userProfileBean.setId_card("");
        userProfileBean.setLast_login_log(null);
        userProfileBean.setAuth_status("");
        userProfileBean.setStatus("NORMAL");
        userProfileBean.setPassword(CyxUtil.buildPswd(publicAttributeBean.getPassword(), userProfileBean.getSalt(), userProfileBean.getPassword_algorithm()));

        UserRegLogBean userRegLogBean  =new UserRegLogBean();
        userRegLogBean.setApp_from(publicAttributeBean.getApp_from());
        JSONObject deviceJson =(JSONObject)JSONObject.toJSON(publicAttributeBean.getDevice());
        userRegLogBean.setDevice(deviceJson.toJSONString());
        userRegLogBean.setInvite("");
        userRegLogBean.setReg_agent(Util.getAgent(Mvcs.getReq()));
        userRegLogBean.setPromo_code("");
        userRegLogBean.setReg_time(Times.now());
        userRegLogBean.setReg_ip(publicAttributeBean.getReq_ip());
        if(publicAttributeBean.getSdk() == null){
            userRegLogBean.setChannel("");
        }else if(publicAttributeBean.getSdk().getChannelId() == null){
            userRegLogBean.setChannel("");
        }else {
            userRegLogBean.setChannel(publicAttributeBean.getSdk().getChannelId() + "|");
        }
        userRegLogBean.setSource("USERNAME");
        userRegLogBean.setUser_id(null);
        JSONObject userReglogJson =(JSONObject)JSONObject.toJSON(userRegLogBean);
        userReglogJson.put("req_loaction", publicAttributeBean.getReq_loaction());/**根据淘宝获取,从前面传过来User*/
        /**存为存入User*/
        userProfileBean.setReg_log(userReglogJson.toJSONString());
        userMapper.add_user_profile(userProfileBean);
        userRegLogBean.setUser_id(userProfileBean.getId());
        userRegLogsMapper.add_reg_logs(userRegLogBean);

        Map<String, Object> data = new HashMap<>();
        data.put("username", userProfileBean.getUsername());
        data.put("password", publicAttributeBean.getPassword());
        return success(data);
    }



    /**
     * 重置修改密码
     */
    @Override
    @Transactional
    public ResData reset_pswd(UserProfileBean userProfileBean,SendSms sendSms) {
        /**判断用户是否存在*/
        List<UserProfileBean> userProfileBeans = userMapper.get_user_profile_List(new  UserProfileBean(userProfileBean.getUsername()));
        if(userProfileBeans.size() == 0){
            Log.e("用户名不存在");
            return failed(ErrorCode.USER_NOT_FOUND.getCode(), ErrorCode.USER_NOT_FOUND.getMsg(),null);
        }
       UserProfileBean newUserProfileBean = userProfileBeans.get(0);
        /**判断手机是否绑定*/
        List<UserAccountsBean> newuserAccountsBeans = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(newUserProfileBean.getId(),"PHONE"));
        if (newuserAccountsBeans.size() == 0){
            Log.e("手机未绑定");
            return failed(ErrorCode.USER_UNBUNDLED_MOBILE.getCode(),ErrorCode.USER_UNBUNDLED_MOBILE.getMsg(),null);
        }
        UserAccountsBean  userAccountsBeanSendSms = newuserAccountsBeans.get(0);
        /**生成新的密码*/
        logger.info(userProfileBean.getPassword());
        newUserProfileBean.setSalt(R.UU64());
        newUserProfileBean.setPassword(CyxUtil.buildPswd(userProfileBean.getPassword(), newUserProfileBean.getSalt(), newUserProfileBean.getPassword_algorithm()));
        userMapper.update_user_profile(newUserProfileBean);

        sendSms.setMobilePhone(userAccountsBeanSendSms.getOpen_id());
        sendSms.setBody( "【" + sendSms.getBody() + "】您的密码为：" + userProfileBean.getPassword()   );
        System.out.println("---------------重置密码为（" + userProfileBean.getPassword() + "）------------------------");
        Boolean flag= MsgUtil.sentMsg(sendSms);
        if(flag){
            return success("密码重置成功");
        }
        return success("密码重置失败");
    }



    /**
     * 重置密码
     */
    @Override
    @Transactional
    public ResData reset_password(UserProfileBean userProfileBean,SendSms sendSms) {
        /**判断手机是否绑定*/
        List<UserAccountsBean> newUserAccountsBeans = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(userProfileBean.getUsername(),"PHONE"));
        if (newUserAccountsBeans.size() == 0){
            Log.e("手机未绑定");
            return failed(ErrorCode.USER_UNBUNDLED_MOBILE);
        }
        UserAccountsBean  userAccountsBeanSendSms = newUserAccountsBeans.get(0);

        /**判断用户是否存在*/
        UserProfileBean newUserProfileBean = userMapper.get_user_profile_info(new UserProfileBean(userAccountsBeanSendSms.getUser_id()));
        if(StringUtils.isEmpty(newUserProfileBean)){
            Log.e("用户名不存在");
            return failed(ErrorCode.USER_USERNAME_PASSWORD_ERROR);
        }
        /**生成新的密码*/
        String password = R.captchaNumber(6);
        newUserProfileBean.setSalt(R.UU64());
        newUserProfileBean.setPassword(CyxUtil.buildPswd(password, newUserProfileBean.getSalt(), newUserProfileBean.getPassword_algorithm()));
        userMapper.update_user_profile(newUserProfileBean);

        sendSms.setMobilePhone(userAccountsBeanSendSms.getOpen_id());
        sendSms.setBody( "【" + sendSms.getBody() + "】您的密码为：" + password  );
        System.out.println("---------------重置密码为（" + password + "）------------------------");
        boolean flag =MsgUtil.sentMsg(sendSms);
        if (flag){
            return success("重置密码成功");
        }
        return failed("null","重置密码失败",null);
    }



    /**
     * 验证手机验证码
     */
    @Override
    @Transactional
    public ResData validate_phone_code(PublicAttributeBean publicAttributeBean) {
        /**判断缓存*/
        String key = buildAuthCodeRedisKey(publicAttributeBean.getTarget(),null,publicAttributeBean.getAction());
        logger.info("Key为"+key);
        if (!redisService.exists(key)){
            Log.e("缓存值不存在");
            return failed(ErrorCode.USER_AUTHCODE_TIME_LIMIT.getCode(),ErrorCode.USER_AUTHCODE_TIME_LIMIT.getMsg(),null);
        }
        UserAuthCodeBean userAuthCodeThirdBean = Json.fromJson(UserAuthCodeBean.class, String.valueOf(redisService.get(key)));
        if(!publicAttributeBean.getCode().equals(userAuthCodeThirdBean.getCode())){
            return failed(ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getCode(),ErrorCode.USER_AUTHCODE_VALIDATION_ERROR.getMsg(),null);
        }
        userAuthCodeThirdBean.setStatus("CONSUMED");
        userAuthCodeMapper.update_user_auth_code(userAuthCodeThirdBean);
        return success(true);
    }

    /**
     * 发送手机验证码
     */
    @Override
    @Transactional
    public ResData send_phone_code(PublicAttributeBean publicAttributeBean,SendSms sendSms) {
        String Code = R.captchaNumber(4);
        UserAuthCodeBean newUserAuthCodeBean = new UserAuthCodeBean();
        newUserAuthCodeBean.setAction(publicAttributeBean.getAction().toUpperCase());
        newUserAuthCodeBean.setTarget(publicAttributeBean.getTarget());
        newUserAuthCodeBean.setCreate_time(Times.now());
        newUserAuthCodeBean.setExpire_time(Times.nextMinute(newUserAuthCodeBean.getCreate_time(), 5));
        newUserAuthCodeBean.setCode(Code);
        newUserAuthCodeBean.setUser_id(publicAttributeBean.getUser_id());
        newUserAuthCodeBean.setStatus("SENT");
        newUserAuthCodeBean.setTarget_type("PHONE");

        logger.info("过期时间"+(newUserAuthCodeBean.getExpire_time().getTime()-newUserAuthCodeBean.getCreate_time().getTime())/1000);

        userAuthCodeMapper.add_user_auth_code(newUserAuthCodeBean);
        logger.info("Key为："+buildAuthCodeRedisKey(publicAttributeBean.getTarget(),null,publicAttributeBean.getAction()));
        logger.info("Value为："+Json.toJson(newUserAuthCodeBean));
        /**存入缓存*/
        String key = buildAuthCodeRedisKey(publicAttributeBean.getTarget(),null,publicAttributeBean.getAction());
        redisService.set(  key,  Json.toJson(newUserAuthCodeBean),(newUserAuthCodeBean.getExpire_time().getTime()-newUserAuthCodeBean.getCreate_time().getTime())/1000);
        sendSms.setMobilePhone(publicAttributeBean.getTarget());
        sendSms.setBody( "【" + sendSms.getBody() + "】您的验证码为:"+Code  );
        boolean flag =MsgUtil.sentMsg(sendSms);
        if (flag){
            return success("发送成功");
        }
        return success("发送失败");
    }




    /**
     * 实名认证
     */
    @Override
    @Transactional
    public ResData validate_realname(PublicAttributeBean publicAttributeBean) {
        UserProfileBean  newUserProfileBean = userMapper.get_user_profile_info(new UserProfileBean(publicAttributeBean.getUser_id()));
        if(StringUtils.isEmpty(newUserProfileBean)){
            Log.e("用户不存在");
            return failed(ErrorCode.USER_NOT_FOUND.getCode(), ErrorCode.USER_NOT_FOUND.getMsg(),null);
        }
        /**判断用户是否已经实名*/
        if (Strings.equalsIgnoreCase(newUserProfileBean.getAuth_status(), "VERIFIED") || Strings.equalsIgnoreCase(newUserProfileBean.getAuth_status(), "VERIFYING")) {
            Log.e("用户已经实名");
            return failed(ErrorCode.USER_HAS_BEEN_AUTHENTICATED.getCode(),ErrorCode.USER_HAS_BEEN_AUTHENTICATED.getMsg(),null);
        }
        /**进行实名验证*/
        newUserProfileBean.setRealname(publicAttributeBean.getRealname());
        newUserProfileBean.setAuth_status("VERIFYING");
        newUserProfileBean.setId_card(publicAttributeBean.getId_card());
        userMapper.update_user_profile(newUserProfileBean);
        /**返回回实名验证状态*/
        ReturnAttributeBean returnAttributeBean  = new ReturnAttributeBean();
        returnAttributeBean.setRealname(newUserProfileBean.getRealname());
        returnAttributeBean.setId_card(newUserProfileBean.getId_card());
        returnAttributeBean.setAuth_status(true);

        return success(returnAttributeBean);
    }



    /**
     * 验证对应的用户是否存在
     */
    @Override
    public ResData verify_exist(PublicAttributeBean publicAttributeBean) {
        /**查用户名*/
        List<UserProfileBean>  userProfileBeans = userMapper.get_user_profile_List(new UserProfileBean(publicAttributeBean.getObj()));
        if(userProfileBeans.size() != 0){
            Log.e("用户已存在");
            return failed(ErrorCode.USER_FOUND.getCode(),ErrorCode.USER_FOUND.getMsg(),null);
        }
        /**查查手机用户*/
        List<UserAccountsBean>userAccountsBeans = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(publicAttributeBean.getObj(),"PHONE"));
        if(userAccountsBeans.size() != 0){
            Log.e("用户已存在");
            return failed(ErrorCode.USER_FOUND.getCode(),ErrorCode.USER_FOUND.getMsg(),null);
        }
        /**查邮箱用户*/
        List<UserAccountsBean>userAccountsBeans1 = userAccountsMapper.select_user_accounts_list(new UserAccountsBean(publicAttributeBean.getObj(),"EMAIL"));
        if(userAccountsBeans1.size() != 0){
            Log.e("用户已存在");
            return failed(ErrorCode.USER_FOUND.getCode(),ErrorCode.USER_FOUND.getMsg(),null);
        }
        return  success(null);
    }

    /**
     * 验证对应的用户是否实名
     */
    @Override
    public ResData realname_exist(PublicAttributeBean publicAttributeBean) {
        UserProfileBean userProfileBean = new UserProfileBean();
        userProfileBean.setId(publicAttributeBean.getUser_id());
        userProfileBean =  userMapper.get_user_profile_info(userProfileBean);

        if(StringUtils.isEmpty(userProfileBean)){
            Log.e("用户不存在");
            return failed(ErrorCode.USER_NOT_FOUND.getCode(),ErrorCode.USER_NOT_FOUND.getMsg(),null);
        }

        /**判断用户是否已经实名*/
        if (Strings.equalsIgnoreCase(userProfileBean.getAuth_status(), "VERIFIED") || Strings.equalsIgnoreCase(userProfileBean.getAuth_status(), "VERIFYING")) {
            return failed(ErrorCode.USER_HAS_BEEN_AUTHENTICATED.getCode(),ErrorCode.USER_HAS_BEEN_AUTHENTICATED.getMsg(),null);
        }
        return success("用户未实名");
    }




    //方法一：
    protected String buildAuthCodeRedisKey(String target, Integer integer, String action) {

        StringBuffer sb = new StringBuffer("authCode:" + action);
        if (!StringUtils.isEmpty(integer)) {
            sb.append(":").append(integer);
        }
        sb.append(":").append(target);
        return "user:" + sb.toString();
    }

    //方法二;
    protected  void setToken(UserTokenBean userTokenBean , UserTokenBean  newUserTokenBean ,UserProfileBean userProfileBean){

        if(StringUtils.isEmpty(userTokenBean)){
            newUserTokenBean.setUser_id(userProfileBean.getId());
            userTokenMapper.add_user_token(newUserTokenBean);
        }else {
            newUserTokenBean.setUser_id(userTokenBean.getUser_id());
            userTokenMapper.update_user_token(newUserTokenBean);
        }
        logger.info("token保存时间:"+validity);
        redisService.set("user:token:" + newUserTokenBean.getUser_id(), Json.toJson(newUserTokenBean), validity);
    }



    //方法三
    protected String  setSdk(PublicAttributeBean publicAttributeBean){
        if(publicAttributeBean.getSdk() == null){
            return "";
        }else if(publicAttributeBean.getSdk().getChannelId() == null){
            return "";
        }else {
            return publicAttributeBean.getSdk().getChannelId() + "|";
        }
    }

}
